package com.jsx.hyyscript.common.exception;

import com.jsx.hyyscript.common.domian.ParameterErrorBack;
import com.jsx.hyyscript.common.domian.RI;
import com.jsx.hyyscript.common.finalfiled.ResultCode;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ValidationException;
import java.util.List;

/**
 * @author sui-b
 * @date 2020/7/6 17:54
 */
@RestControllerAdvice(value = {"com.jsx.hyyscript","org.apache.tomcat.util.http.fileupload.impl"})
public class GlobalExceptionHandler {

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public RI parameterExceptionHandler(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        if (bindingResult.hasErrors()) {
            List<ObjectError> allErrors = bindingResult.getAllErrors();
            if (allErrors.size() != 0) {
                FieldError objectError = (FieldError) allErrors.get(0);
                return new ParameterErrorBack(objectError.getDefaultMessage());
            }
        }
        return new ParameterErrorBack("error");
    }

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(HyyException.class)
    public RI parameterExceptionHandler2(HyyException e) {
        return new ParameterErrorBack(e.getResultCode(), e.getResultMessage());
    }

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(ValidationException.class)
    public RI parameterValidationException(ValidationException e) {
        return new ParameterErrorBack(ResultCode.PARAMETER_ERROR, e.getMessage());
    }


}
